<?php


namespace App\Model\Logic;

use App\Helper\RedisConst;
use Swoft\Bean\Annotation\Mapping\Bean;
use Swoft\Bean\Annotation\Mapping\Inject;
use Swoft\Redis\Pool;

/**
 * @Bean()
 * 点赞逻辑
 * Class PraiseLogic
 * @package App\Model\Logic
 */
class PraiseLogic
{

    /**
     * @Inject("redis2.pool")
     * @var Pool
     */
    private $redis2;

    /**
     * --------------------------------------------------------------------------
     * 批量获取post点赞状态
     * --------------------------------------------------------------------------
     * @param $member_id
     * @param $post_ids
     * @return mixed
     */
    public function multiPraised($member_id, $post_ids)
    {
        $func = function($pipe) use($member_id, $post_ids){
            foreach($post_ids as $post_id){
                $key = RedisConst::POSTNEWPRAISE . $post_id;
                $pipe->ZREVRANK($key, $member_id);
            }
        };
        return $this->redis2->pipeline($func);
    }

    /**
     * 判断是否点赞过
     * @param $member_id
     * @param $post_id
     * @return bool
     */
    public function isPraised($member_id, $post_id)
    {
        $key = RedisConst::POSTNEWPRAISE . $post_id;
        $res = $this->redis2->zREVRANK($key, $member_id);
        return is_numeric($res) ? true : false;
    }


    //点赞数据加入缓存
    public function addCache($member_id, $post_id)
    {
        $key = RedisConst::POSTNEWPRAISE . $post_id;
        $score = time() . rand(1000, 9999);
        $this->redis2->zAdd($key, $score, $member_id);
    }


    //取消点赞 移除缓存
    public function rmCache($member_id, $post_id)
    {
        $key = RedisConst::POSTNEWPRAISE . $post_id;
        return $this->redis2->zRem($key, $member_id);
    }


}